using System;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;

namespace PHMEE.Managers.Diagnosis;

/// <summary>
/// 轴承参数领域服务
/// </summary>
public class BearingParametersDomainService : DomainService, IBearingParametersDomainService
{
    private readonly IReadOnlyRepository<BearLib, Guid> _bearLibReadOnlyRepository;

    public BearingParametersDomainService(IReadOnlyRepository<BearLib, Guid> bearLibReadOnlyRepository)
    {
        _bearLibReadOnlyRepository = bearLibReadOnlyRepository;
    }
    
    /// <inheritdoc />
    public async Task<float[]> GetBearingParametersAsync(int bearFactoryId, string model)
    {
        // 当 model 为 NA 时，表示没有该轴承，则返回四个项均为 0 的数组
        if (string.IsNullOrWhiteSpace(model) || string.Equals(model, "NA"))
        {
            return [0f, 0f, 0f, 0f];
        }
        
        var bearEntity = await _bearLibReadOnlyRepository
            .FirstOrDefaultAsync(b => b.BearFactoryId == bearFactoryId && b.Model == model);
        if (bearEntity == null)
        {
            throw new InvalidOperationException($"There is no bearing with factoryId: {bearFactoryId} and model: {model}");
        }

        return
        [
            (float)bearEntity.BPFI,
            (float)bearEntity.BPFO,
            (float)bearEntity.BSF,
            (float)bearEntity.FTFI
        ];
    }
}

/// <summary>
/// 轴承参数领域服务接口
/// </summary>
public interface IBearingParametersDomainService
{
    /// <summary>
    /// 获取轴承参数
    /// </summary>
    /// <param name="bearFactoryId"></param>
    /// <param name="model"></param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    Task<float[]> GetBearingParametersAsync(int bearFactoryId, string model);
}